//
//  DataOutputStream.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-15.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "DataOutputStream.h"


@implementation DataOutputStream

- (id)init{
	if(self = [super init]){
		data = [[NSMutableData alloc] init];
		length = 0;
	}
	return self;
}

- (NSInteger)write:(NSInteger)b{
	char ch[1];
	ch[0] = (b & 0x0ff);
	[data appendBytes:ch length:1];
	length++;
	return 1;
}

- (void)writeShort:(NSInteger)s{
	char ch[2];
	ch[0] = (s & 0x0ff00)>>8;
	ch[1] = (s & 0x0ff);
	[data appendBytes:ch length:2];
	length = length + 2;
}

- (void)writeInt:(NSInteger)iv{
	char ch[4];
	
	for(int i = 0;i<4;i++){
		ch[i] = ((iv >> ((3 - i)*8)) & 0x0ff);
	}
	[data appendBytes:ch length:4];
	length = length + 4;
}

- (void)writeLong:(long)l{
	char ch[8];
	for(int i = 0;i<8;i++){
		ch[i] = ((l >> ((7 - i)*8)) & 0x0ff);
	}
	[data appendBytes:ch length:8];
	length = length + 8;
}

- (void)writeUTF:(NSString *)str{
	NSData *d = [str dataUsingEncoding:NSUTF8StringEncoding];
	NSInteger len = [d length];
	[self writeShort:len];
	[data appendData:d];
	length = length + len;
}

- (NSInteger)writeBytes:(NSData *)bytes{
	[data appendData:bytes];
	NSInteger len = [bytes length];
	length = length + len;
	return len;
}

- (NSData *)toByteArray{
	return data;
}

- (void)dealloc{
	[data release];
	[super dealloc];
}

@end
